package com.jxc.realm;

import com.jxc.entity.User;
import com.jxc.repository.UserRepository;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * 自定义realm
 *
 * @author 高旭
 * @date 2021-03-20
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserRepository userRepository;

    /**
     * 授权
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 权限认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //因为用户的密码是加密存储在数据库中的，不支持反向破解，所以根据用户姓名查出用户，返回查出的用户与输入的用户对比
        String userName = (String) authenticationToken.getPrincipal();
        User user = userRepository.findOneByUserName(userName);
        if (user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getUserName(), user.getPassword(), "xxx随便输入");
            return authcInfo;
        } else {
            return null;
        }
    }
}
